package com.anttribe.components.db.metadata.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import javax.sql.DataSource;

import com.anttribe.components.db.metadata.Dialect;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhaoyong
 * @date 2020-12-27
 */
@Slf4j
public class DataSourceProxy implements DataSource {

    private DataSource dataSource;

    /**
     * 数据库方言(数据库类型)
     */
    private Dialect dialect;

    public DataSourceProxy(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public Connection getConnection(String username, String password) throws SQLException {
        return dataSource.getConnection(username, password);
    }

    public <T> T unwrap(Class<T> iface) throws SQLException {
        return dataSource.unwrap(iface);
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return dataSource.isWrapperFor(iface);
    }

    public PrintWriter getLogWriter() throws SQLException {
        return dataSource.getLogWriter();
    }

    public void setLogWriter(PrintWriter out) throws SQLException {
        dataSource.setLogWriter(out);
    }

    public void setLoginTimeout(int seconds) throws SQLException {
        dataSource.setLoginTimeout(seconds);
    }

    public int getLoginTimeout() throws SQLException {
        return dataSource.getLoginTimeout();
    }

    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return dataSource.getParentLogger();
    }

    public Dialect getDialect() throws SQLException {
        if (null == dialect) {
            // 根据请求的url中判断数据库类型
            String jdbcUrl = this.getConnection().getMetaData().getURL();
            dialect = Dialect.decideDialect(jdbcUrl);
        }
        return dialect;
    }
}
